/*
 * 
 */
package com.techventus.locations;


import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
//import java.util.Timer;
//import java.util.TimerTask;


import android.app.Activity;
//import android.content.ComponentName;
//import android.content.Context;
import android.content.Intent;
//import android.content.ServiceConnection;
import android.content.pm.ActivityInfo;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
//import android.os.IBinder;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
//import android.widget.Toast;

public class MainMenu extends Activity {
	boolean mIsBound = false;
//	String authToken;
//	String source = "a";
	//String urlString = "https://www.google.com/accounts/ManageAccount";
//	String urlString = "https://www.google.com/voice/";
	
	Timer timer =new Timer();
	
	/*
	private TimerTask statuscheck(){
		TimerTask statuscheck = new TimerTask(){
	
			@Override
			public void run() {
				
				setDisplay();
				
			}
			
		};
		return statuscheck;
	}
	*/
//	private LocationService mBoundService;
//	
//	/** The m connection. */
//	private ServiceConnection mConnection = new ServiceConnection() {
//		@Override
//	    public void onServiceConnected(ComponentName className, IBinder service) {
//	        // This is called when the connection with the service has been
//	        // established, giving us the service object we can use to
//	        // interact with the service.  Because we have bound to a explicit
//	        // service that we know is running in our own process, we can
//	        // cast its IBinder to a concrete class and directly access it.
//	        mBoundService = ((LocationService.LocalBinder)service).getService();
//
//	        // Tell the user about this for our demo.
//	        Toast.makeText(MainMenu.this, "Connected",
//	                Toast.LENGTH_SHORT).show();
//	    }
//		@Override
//	    public void onServiceDisconnected(ComponentName className) {
//	        // This is called when the connection with the service has been
//	        // unexpectedly disconnected -- that is, its process crashed.
//	        // Because it is running in our same process, we should never
//	        // see this happen.
//	        mBoundService = null;
//	        Toast.makeText(MainMenu.this, "Disconn",
//	                Toast.LENGTH_SHORT).show();
//	    }
//
//
//	};
//	
//	
	
	
	
	
	TextView gpsTextView  ;
	TextView locationNameView  ;
	
	
	
	
	TimerTask startServiceTask = new TimerTask(){

		@Override
		public void run() {
			try{
		        Log.e("TECHVENTUS","STARTING SERVICE");
		        Intent serviceIntent = new Intent(MainMenu.this,LocationService.class);
		        startService(serviceIntent);
			}catch(Exception o){
				Log.e("TECHVENTUS","EXCEPTION IN MainMenu.startServiceTask");
				o.printStackTrace();
			}
		}
		
	};
	
	TimerTask startLoginProcedureTask = new TimerTask(){

		@Override
		public void run() {
			// TODO Auto-generated method stub
			 
		       // setDisplay();
		        boolean startLoginProcedure = false;
		        
		        	try{
		        		synchronized(this){
				        	 SQLiteDatabase sql = openOrCreateDatabase("db",0,null);
				        	 Cursor c = sql.rawQuery("SELECT * FROM GOOGLE;", null);
				        	 try{
					        	 
					        	 
					        	 if(c!=null){
						        	 if(!c.moveToNext()){
						        		 startLoginProcedure = true;
				
						        	 }else{
						        		 startLoginProcedure = false;
						        	 }
						        	 
						        	 //c.close();
						        	 
					        	 }else{
					        		 startLoginProcedure = true;
					        	 }																	
				        	 }catch(Exception u){
				        		 u.printStackTrace();
				        	 }finally{
				        		 c.close();
				        		 sql.close();
				        	 }
			        	// sql.close();
		        		}//synch
		        	 
		        	 if(startLoginProcedure){
		        		 Intent i = new Intent(MainMenu.this,LoginCredentials.class);
		        		 startActivity(i);
		        	 }
		        		
		        }catch(Exception e){
		        	 Log.e("TECHVENTUS","Exception in MainMenu determining credentials - starting LoginCredentials intent");
		        	 e.printStackTrace();
		       		 Intent i = new Intent(MainMenu.this,LoginCredentials.class);
		    		 startActivity(i);
		        }

		}
		
	};
	
	@Override protected void onCreate(Bundle savedInstanceState){
	      super.onCreate(savedInstanceState);
	        this.setContentView(R.layout.main);
	        setRequestedOrientation( ActivityInfo.SCREEN_ORIENTATION_PORTRAIT ); 
	        
	        timer.schedule(startServiceTask, 7000);
	        /*
	        Log.e("TECHVENTUS","STARTING SERVICE");
	        Intent serviceIntent = new Intent(this,LocationService.class);
	        startService(serviceIntent);
	        */
	      //  bindService(serviceIntent, mConnection, Context.BIND_AUTO_CREATE);

	       

	        
	        Button locationsButton = (Button)findViewById(R.id.mainlocationsbutton);
	        Button settingsButton = (Button)findViewById(R.id.mainsettingsbutton);
	        Button dialerButton = (Button)findViewById(R.id.DialerButton);
	       //Button closeButton = (Button)findViewById(R.id.CloseButton);
	        gpsTextView = (TextView)findViewById(R.id.maingpscoords);
	        settingsButton.setOnClickListener(settingsClick);
	        locationsButton.setOnClickListener(locationsClick);
	        dialerButton.setOnClickListener(dialerClick);
	        //closeButton.setOnClickListener(closeClick);
	        locationNameView = (TextView)findViewById(R.id.currentlocationname);

	        
	        timer.schedule(startLoginProcedureTask, 2000);
	        
	       
	}
	
	OnClickListener settingsClick = new OnClickListener(){

		@Override
		public void onClick(View arg0) {
			 Intent i = new Intent(MainMenu.this, SettingsMenu.class);
			startActivity(i);
		}
		
	};
	
	OnClickListener dialerClick = new OnClickListener(){

		@Override
		public void onClick(View arg0) {
			 Intent i = new Intent(MainMenu.this, Dialer.class);
			startActivity(i);
		}
		
	};
	
	OnClickListener closeClick = new OnClickListener(){

		@Override
		public void onClick(View arg0) {
			MainMenu.this.finish();
			
		}
		
	};
	
	
	
	OnClickListener locationsClick = new OnClickListener(){

		@Override
		public void onClick(View arg0) {
			
			SQLiteDatabase sql = openOrCreateDatabase("db",0,null);
			
			String[] LOCATIONS = getStringArSQLVertical("SELECT locationName from LOCATIONS;",sql);

			sql.close();
			
			
			
			Intent i = new Intent(MainMenu.this, LocationsMenu.class);
			i.putExtra("locations",LOCATIONS);
			startActivity(i);
			
			
			
			
			
		}
		
	};
	
	
	@Override
	protected void onResume(){
		super.onResume();
		setDisplay();
       
        //timer.schedule(statuscheck)
        //timer.schedule(statuscheck(), 3000);
	}
	
	private void setDisplay(){

		int lat=0;
		int lon=0;
		String place = "Unknown";
		try{
			SQLiteDatabase sql = openOrCreateDatabase("db",0,null);
			try{
				
				
					synchronized(this){
					
							String queryString = "SELECT status FROM STATUS WHERE key = 'latitude';";
							
							Cursor c = sql.rawQuery(queryString, null);
							
							try{
								if(c!=null){
										if(c.moveToNext()){
											lat = Integer.parseInt(c.getString(0));
											System.out.println(lat);
										}
										//c.close();
								}
							}catch(Exception y){
								y.printStackTrace();
							}finally{
								c.close();
							}
						
					}
					synchronized(this){
						String queryString = "SELECT  status FROM STATUS WHERE key = 'longitude';";
						
						 Cursor c = sql.rawQuery(queryString, null);
						try{
							 if(c!=null){
								 if(c.moveToNext()){
									 lon = Integer.parseInt(c.getString(0));
									 System.out.println(lon);
								 }
								 //c.close();
							 }
						}catch(Exception y){
							y.printStackTrace();
						}finally{
							c.close();
						}
					}
				
					synchronized(this){
					
						String queryString = "SELECT  status FROM STATUS WHERE key = 'location';";
						
						Cursor c = sql.rawQuery(queryString, null);
						try{
							 if(c!=null){
								 if(c.moveToNext()){
									 place = c.getString(0);
									 System.out.println(place);
								 }
								
							 }
						}catch(Exception y){
							y.printStackTrace();
						}finally{
							c.close();
						}
					}
				
				}catch(Exception e){
					e.printStackTrace();
				}finally{
					
					sql.close();
				}
				
			//c.moveToNext();
			
			//place = c.getString(0);
			
			//c.close();
			
			
		}catch(Exception e){
			Log.e("TECHVENTUS","Exception in MainMenu Lat Lon ping");
			System.out.println("");
			e.printStackTrace();
			lat = 0;
			lon = 0;
			
		}
		
		if(lat!=0&&lon!=0){
			DecimalFormat nf = new DecimalFormat("###.00000");
			gpsTextView.setText("LAT: "+nf.format((double)lat/((double)1E6)) +" LON: "+nf.format((double)lon/(double)1E6));
			locationNameView.setText(place);
		}else{		
			gpsTextView.setText("LAT: -XXX.XXXXX LON: -XXX.XXXXX");
			locationNameView.setText("Unknown");
		}
	}
	
	
	@Override
	protected void onDestroy() {
		
	    super.onDestroy();
	    //doUnbindService();
	   
	}
	/*
	void doUnbindService() {
	    if (mIsBound) {
	        // Detach our existing connection.
	        unbindService(mConnection);
	        mIsBound = false;
	    }
	}
	*/
	/*
	void doBindService() {
	    // Establish a connection with the service.  We use an explicit
	    // class name because we want a specific service implementation that
	    // we know will be running in our own process (and thus won't be
	    // supporting component replacement by other applications).
		System.out.println("****************************");
		Log.e("TECHVENTUS","BINDING NOW");
	    bindService(new Intent(MainMenu.this, 
	    		//?????LocationService
	            LocationService.class), mConnection, Context.BIND_AUTO_CREATE);
	    mIsBound = true;
	    Log.e("TECHVENTUS","misBound "+mIsBound);
	}
	*/

	private String[] getStringArSQLVertical(String query, SQLiteDatabase sql){
		String[] ret = new String[0];
		try{
			Cursor c = sql.rawQuery(query, null);
			try{
				List<String> list = new ArrayList<String>();
				if(c!=null){
					while(c.moveToNext()){
						list.add(c.getString(0));
						Log.e("TECHVENTUS",c.getString(0));
						
					}
					if(list.size()>0){
						ret = new String[list.size()];
						for(int i=0;i<list.size();i++){
							ret[i] = list.get(i);
						}
					}
					//c.close();
				}
			}catch(Exception o){
				Log.e("TECHVENTUS","EXCEPTION IN getStringArSQLVertical "+query);
				o.printStackTrace();
			}finally{
				c.close();
			}

			//c.getString(0);
			
		}catch(Exception o){
			
			o.printStackTrace();
		}
		return ret;
	}
	
/*
	public void login() throws IOException{

		String data = URLEncoder.encode("accountType", "UTF-8") + "="
				+ URLEncoder.encode("GOOGLE", "UTF-8");
		data += "&" + URLEncoder.encode("Email", "UTF-8") + "="
				+ URLEncoder.encode(user, "UTF-8");
		data += "&" + URLEncoder.encode("Passwd", "UTF-8") + "="
				+ URLEncoder.encode(pass, "UTF-8");
		data += "&" + URLEncoder.encode("service", "UTF-8") + "="
				+ URLEncoder.encode("grandcentral", "UTF-8");
		data += "&" + URLEncoder.encode("source", "UTF-8") + "="
				+ URLEncoder.encode(source, "UTF-8");

		// Send data
		URL url = new URL("https://www.google.com/accounts/ClientLogin");
		URLConnection conn = url.openConnection();
		conn.setDoOutput(true);
		OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
		wr.write(data);
		wr.flush();

		// Get the response
		BufferedReader rd = new BufferedReader(new InputStreamReader(conn
				.getInputStream()),1024);
		String line;

		//String AuthToken = null;
		while ((line = rd.readLine()) != null) {
			// System.out.println(line);
			if (line.contains("Auth=")) {
				this.authToken = line.split("=", 2)[1].trim();
				System.out.println("AUTH TOKEN =" + this.authToken);
			}
		}
		wr.close();
		rd.close();

		if (this.authToken == null) {
			throw new IOException("No Authorisation Received.");
		}
	}
	
	
	void openNext(){
		try{
			URL url = new URL(urlString+"?auth="+URLEncoder.encode(authToken,"UTF-8"));
			URLConnection conn = url.openConnection ();
			//Log.e("TECHVENTUS",conn.getRequestProperty("User-agent"));
			conn.setRequestProperty("User-agent", "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US) AppleWebKit/525.13 (KHTML, like Gecko) Chrome/0.A.B.C Safari/525.13");
	//"Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US) AppleWebKit/525.13 (KHTML, like Gecko) Chrome/0.A.B.C Safari/525.13"
			// Get the response
			BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()),1024);
			StringBuffer sb = new StringBuffer();
			String line;
			while ((line = rd.readLine()) != null)
			{
				sb.append(line+"\n\r");
			}
			rd.close();
			String result = sb.toString();
			Log.e("TECHVENTUS",result);
			System.out.println(result);
		}catch(Exception e){
			e.printStackTrace();
		}
	}
	*/
}
